﻿#r @"..\Microsoft.SharePoint.Client (spo)\Microsoft.SharePoint.Client.dll"
#r @"..\Microsoft.SharePoint.Client (spo)\Microsoft.SharePoint.Client.Runtime.dll"

#load "Client.fs"

open Client
open Microsoft.SharePoint.Client
open Microsoft.SharePoint.Client.Application
open System.Security

// =======================================================
// Work with items and metadata
// =======================================================

let list = Client.Context.Web.Lists.GetByTitle("Documents")

Client.Load list

let item = list.GetItemById(1)
Client.Load item

// Read all metadata for item
for fld in item.FieldValues do
    let mutable key = ""    
    if not (fld.Value = null) then
        key <- "Key: " + fld.Key.ToString() + " | "
    let mutable value = "";
    if not (fld.Value = null) then
        value <- "Value: " + fld.Value.ToString()
    let msg = key + " " + value
    printfn "%s\n" msg

    
//// ===========================================================
//// ==== Create new items as batch
//// ===========================================================
let user = Client.Context.Web.EnsureUser("me@geek.onmicrosoft.com")
Client.Load user

for i in 1..50 do
    let itemInfo = new ListItemCreationInformation()
    itemInfo.LeafName <- "TestItem " + i.ToString()
    let item = list.AddItem(itemInfo)
    item.["Title"] <- "TestItem " + i.ToString()
    item.["Description"] <- "TestItem " + i.ToString()
    item.["User"] <- user
    item.Update()
    Client.ExecuteQuery()
        

// ===========================================================
// Batch load and update items
// ===========================================================
for i in 478..478 do
    let item = list.GetItemById(i)
    Client.Load item
    Client.Context.Load(item, (fun (i:ListItem) -> i.["HasUniqueRoleAssignments"]))
    Client.Context.Load(item, (fun (i:ListItem) -> i.["Status"]))
    Client.ExecuteQuery()
    if item.HasUniqueRoleAssignments then
        item.ResetRoleInheritance()
    if item.["Status"].ToString() = "Completed With Errors" then
        item.["Status"] <- "Not Started"
    item.Update()
    Client.ExecuteQuery()